package org.mock.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.mock.entity.SabreHotelDetail;
import org.mock.enums.SabreMockStateEnum;
import org.mock.mapper.SabreHotelDetailMapper;
import org.mock.service.SabreHotelDetailService;
import org.mock.dto.SabreHotelDetailDTO;
import org.mock.common.Condition;
import org.mock.service.SabreMockSceneService;
import org.mock.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import cn.hutool.core.util.StrUtil;

import java.util.List;

/**
 * 服务实现类
 *
 * @author AI
 * @since 2025-05-20
 */
@Service
@AllArgsConstructor
@Slf4j
public class SabreHotelDetailServiceImpl implements SabreHotelDetailService {

    protected SabreHotelDetailMapper sabreHotelDetailMapper;
    private SabreMockSceneService sabreMockSceneService;

    @Override
    public SabreHotelDetailDTO handleRequest(JSONObject request) {
        log.info("[getHotelDetails] 请求：{}", request);
        SabreHotelDetailDTO dto = new SabreHotelDetailDTO();
        try {
            JSONObject requestJson = request.getJSONObject("GetHotelDetailsRQ");
            JSONObject searchCriteria = requestJson.getJSONObject("SearchCriteria");

            JSONObject hotelRefs = searchCriteria.getJSONObject("HotelRefs");
            JSONObject hotelRef = hotelRefs.getJSONObject("HotelRef");
            String hotelCode = hotelRef.get("HotelCode").toString();
            log.info("hotelCode:{}", hotelCode);

            JSONObject rateInfoRef = searchCriteria.getJSONObject("RateInfoRef");
            if (rateInfoRef.containsKey("RatePlanCandidates")) {
                JSONObject ratePlanCandidates = rateInfoRef.getJSONObject("RatePlanCandidates");
                JSONArray ratePlanCandidate = ratePlanCandidates.getJSONArray("RatePlanCandidate");
                String ratePlanCode = ratePlanCandidate.getJSONObject(0).get("RatePlanCode").toString();
                log.info("ratePlanCode:{}", ratePlanCode);
                dto.setRatePlanCode(ratePlanCode);
            }

            JSONObject stayDateTimeRange = rateInfoRef.getJSONObject("StayDateTimeRange");
            String startDate = stayDateTimeRange.get("StartDate").toString();
            String endDate = stayDateTimeRange.get("EndDate").toString();
            log.info("startDate:{}", startDate);
            log.info("endDate:{}", endDate);
            dto.setHotelCode(hotelCode);
            dto.setStartDate(DateUtil.parseDate(startDate));
            dto.setEndDate(DateUtil.parseDate(endDate));
        } catch (Exception e) {
            log.error("请求解析异常：{}", e.getMessage(), e);
        }
        return dto;
    }

    @Override
    public SabreHotelDetailDTO handleQueryWrapper(SabreHotelDetailDTO oldDto) {
        SabreHotelDetailDTO newDto = new SabreHotelDetailDTO();
        String currentMockNo = sabreMockSceneService.getMockNoByStatus(SabreMockStateEnum.ON_REQUEST.getValue());

        if ("000".equals(currentMockNo)) {
            log.info("当前查询模式：忽略所有的查询条件，直接给一个全新的dto");
            return newDto;
        } else if ("102".equals(currentMockNo)) {
            log.info("当前查询模式：请求只带上日期");
            newDto.setStartDate(oldDto.getStartDate());
            newDto.setEndDate(oldDto.getEndDate());
        }
        return newDto;
    }

    @Override
    public String handleData(SabreHotelDetail data, SabreHotelDetailDTO originalQuery) {
        if (ObjectUtil.isEmpty(data)) {
            log.info("暂无数据");
            return StrUtil.EMPTY;
        }
        String response = data.getResponse();
        try {
            String mockNo = sabreMockSceneService.getMockNoByStatus(SabreMockStateEnum.ON_RESPONSE.getValue());
            if ("201".equals(mockNo)) {
                log.info("查询hotel_detail, 返回修改日期，改成请求中的日期");
                String startDate = DateUtil.format(originalQuery.getStartDate(), "yyyy-MM-dd");
                String endDate = DateUtil.format(originalQuery.getEndDate(), "yyyy-MM-dd");

                JSONObject responseJson = JSON.parseObject(response);
                JSONObject hotelRateInfo = responseJson.getJSONObject("GetHotelDetailsRS").getJSONObject("HotelDetailsInfo").getJSONObject("HotelRateInfo");
                JSONArray roomList = hotelRateInfo.getJSONObject("Rooms").getJSONArray("Room");
                for (int i = 0; i < roomList.size(); i++) {
                    log.info("修改日期为 {} ~ {}", startDate, endDate);
                    JSONObject room = roomList.getJSONObject(i);
                    JSONObject ratePlan = room.getJSONObject("RatePlans").getJSONArray("RatePlan").getJSONObject(0);
                    JSONObject rateInfo = ratePlan.getJSONObject("RateInfo");
                    rateInfo.put("StartDate", startDate);
                    rateInfo.put("EndDate", endDate);
                }

                JSONObject rateInfos = hotelRateInfo.getJSONObject("RateInfos");
                if (rateInfos.containsKey("ShopKey")) {
                    log.info("有分页，要删掉，不然会死循环");
                    rateInfos.remove("ShopKey");
                }

                return responseJson.toJSONString();
            }
        } catch (Exception e) {
            log.error("解析返回结构异常", e);
        }
        return response;
    }

    @Override
    public SabreHotelDetail getOne(SabreHotelDetailDTO dto) {
        List<SabreHotelDetail> list = sabreHotelDetailMapper.selectList(Condition.getQueryWrapper(BeanCopyUtils.copy(dto, SabreHotelDetail.class)));
        if (CollUtil.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
//        return sabreHotelDetailMapper.selectOne(Condition.getQueryWrapper(BeanCopyUtils.copy(dto,SabreHotelDetail.class)));
    }
}
